package com.hk.player;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.hk.player.utils.PlayerDataManager;
import com.hk.player.utils.WatermarkUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.MathUtils;
import com.zhoug.common.utils.StringUtils;
import com.zhoug.player.core.OnZoomListener;
import com.zhoug.player.core.OnZoomScaleListener;
import com.zhoug.player.core.VideoRatioTextureView;

/**
 * 播放画面窗口,支持水印,缩放
 * @Author: zhoug
 * @Date: 2023/10/3
 * @Description:
 */
public class PlayerWindowView extends FrameLayout {
    private static boolean DEBUG = false;

    private static final String TAG = ">>>PlayWindowView";
    private boolean isLayoutInit;//布局是否初始化
    private boolean isOpenZoom = false;//电子放大是否打开
    private OnDigitalZoomListener mOnDigitalZoomListener;//电子放大监听
    private OnZoomListener mOnZoomListener;
    private OnZoomScaleListener mOnZoomScaleListener;
    private boolean zoomEnable = false;

    /**
     * 电子放大回调接口是否执行
     */
    private boolean mOpenDigitalZoomListenerCall;
    /**
     * 上一次两指之间的距离
     */
    private float mLastDis;

    private Bitmap mWatermarkBitmap;//水印
    private GestureDetector mGestureDetector;
    private Watermark mWatermark;

    private VideoRatioTextureView mTextureView;
    private ImageView mIvWatermark;
    private TextView mTvZoom;


    public PlayerWindowView(Context context) {
        super(context);
        init();
    }

    public PlayerWindowView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PlayerWindowView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public PlayerWindowView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        if (!isLayoutInit) {
            removeAllViews();
            View root = LayoutInflater.from(getContext()).inflate(R.layout.hk_player_window_view, this, false);
            mTextureView = root.findViewById(R.id.textureView);
            mIvWatermark = root.findViewById(R.id.iv_watermark);
            mTvZoom = root.findViewById(R.id.tv_zoom);
            addView(root);
            isLayoutInit = true;
            mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapConfirmed(MotionEvent e) {
                    if (DEBUG) {
                        LogUtils.d(TAG, "onSingleTapConfirmed:单击");
                    }
                    return performClick();
//                    return true;
                }
            });
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!zoomEnable) {
            return super.onTouchEvent(event);
        }
        boolean b = mGestureDetector.onTouchEvent(event);
        if (b) {
            return true;
        }
        if (DEBUG) {
            LogUtils.d(TAG, "onTouchEvent:" + (event.getAction() & MotionEvent.ACTION_MASK));
        }
        final int action = event.getAction();
        //检测是否是开启关闭电子放大的逻辑
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                mOpenDigitalZoomListenerCall = false;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                mLastDis = spacing(event);
                break;
            case MotionEvent.ACTION_MOVE:
                //如果电子放大已经开启就不需要再次回调
                if (isOpenZoom) {
                    return false;
                }
                if (event.getPointerCount() == 2 && !mOpenDigitalZoomListenerCall) {
                    float dis = spacing(event);
                    if (dis > mLastDis) {
                        //如果当前缩放等级是1，且是放大手势，就开启电子放大，并将触摸事件交给子view
                        isOpenZoom = true;
                        openDigitalZoom();
                        mOpenDigitalZoomListenerCall = true;
                    }
                }
                break;
            default:
                break;
        }
        return true;
    }



    /**
     * 开始电子放大
     */
    private void openDigitalZoom() {
        setZoomViewScale(1.0f);

        mTextureView.setOnZoomListener((oRect, curRect) -> {
            if (mOnDigitalZoomListener != null) {
                mOnDigitalZoomListener.onZoomListener(oRect, curRect);
            }
        });
        mTextureView.setOnZoomScaleListener(scale -> {
            if (scale < 1.0f) {
                //如果已经开启了电子放大且倍率小于1就关闭电子放大
                isOpenZoom = false;
                if (mOnDigitalZoomListener != null) {
                    mOnDigitalZoomListener.onCloseDigital();
                }
                mTextureView.setOnZoomListener(null);
                mTextureView.setOnZoomScaleListener(null);
                hideZoomView();

            } else {
                setZoomViewScale(scale);
            }
        });
    }

    private void setOpenZoom(boolean openZoom) {
        isOpenZoom = openZoom;
    }

    private boolean isOpenZoom() {
        return isOpenZoom;
    }

    /**
     * 当有两个手指按在屏幕上时，计算两指之间的距离
     *
     * @param event 触摸事件
     * @return 两指之间的距离
     */
    private float spacing(MotionEvent event) {
        if (event.getPointerCount() < 2) {
            return 0;
        }
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);

        return (float) Math.sqrt(x * x + y * y);
    }


    public VideoRatioTextureView getTextureView() {
        return mTextureView;
    }

    public ImageView getWatermarkImageView() {
        return mIvWatermark;
    }

    /**
     * 显示并设置当前电子放大倍数
     *
     * @param scale
     */
    private void setZoomViewScale(float scale) {
        if (mTvZoom != null && scale >= 1.0f) {
            if (mTvZoom.getVisibility() != View.VISIBLE) {
                mTvZoom.setVisibility(View.VISIBLE);
            }
            mTvZoom.setText(StringUtils.format("%sX", MathUtils.formatDecimalUp(scale, 1, true)));
        }
    }

    /**
     * 隐藏电子放大倍数
     */
    public void hideZoomView() {
        if (mTvZoom != null && mTvZoom.getVisibility() != View.GONE) {
            mTvZoom.setVisibility(View.GONE);
        }
    }

    /**
     * 设置水印
     *
     * @param watermark
     */
    public void setWatermark(Watermark watermark) {
        if (mWatermark == null || !mWatermark.equals(watermark)) {
//            LogUtils.d(TAG, "setWatermark:水印改变");
            this.mWatermark = watermark;
            PlayerDataManager.getInstance().setWatermark(mWatermark);
            mWatermarkBitmap = WatermarkUtils.createWatermarkBitmap();
        }else{
//            LogUtils.d(TAG, "setWatermark:水印没变");
        }
    }

    /**
     * 显示/隐藏视频水印
     *
     * @param show
     */
    public void showWatermark(boolean show) {
        if (mIvWatermark == null) {
            return;
        }
        if (show) {
            if (mWatermarkBitmap == null) {
                mWatermarkBitmap = WatermarkUtils.createWatermarkBitmap();
            }
            if (mWatermarkBitmap != null) {
                mIvWatermark.setImageBitmap(mWatermarkBitmap);
                setWatermarkVisibility(true);
            } else {
                setWatermarkVisibility(false);
            }
        } else {
            setWatermarkVisibility(false);
        }
    }

    public void setZoomEnable(boolean zoomEnable) {
        this.zoomEnable = zoomEnable;
    }

    /**
     * 设置水印的显示状态
     *
     * @param show
     */
    private void setWatermarkVisibility(boolean show) {
        if (mIvWatermark != null) {
            mIvWatermark.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }


    public interface OnDigitalZoomListener {
        /**
         * 开启电子放大
         */
        void onZoomListener(Rect oRect, Rect curRect);

        /**
         * 关闭电子放大
         */
        void onCloseDigital();

    }

    public void setOnDigitalZoomListener(OnDigitalZoomListener onOpenDigitalZoomListener) {
        this.mOnDigitalZoomListener = onOpenDigitalZoomListener;
    }


}
